package com.sgcc.ln.pmos.mobileapp.activity;

import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.sgcc.ln.pmos.arouter.app.AppArouterPath;
import com.sgcc.ln.pmos.common.base.MvpBaseActivity;
import com.sgcc.ln.pmos.common.bean.EventCenter;
import com.sgcc.ln.pmos.common.bean.FaceGetCodeBean;
import com.sgcc.ln.pmos.common.http.HttpInterConst;
import com.sgcc.ln.pmos.common.http.HttpRequestUtils;
import com.sgcc.ln.pmos.common.http.MvcNetCallback;
import com.sgcc.ln.pmos.common.utils.ArguConstant;
import com.sgcc.ln.pmos.common.utils.DialogUtil;
import com.sgcc.ln.pmos.common.utils.SysUtil;
import com.sgcc.ln.pmos.common.utils.XXPermissionsUtil;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.ln.pmos.mobileapp.bean.DoLoginReleaseBean;
import com.sgcc.ln.pmos.mobileapp.contract.VideoAttestationContract;
import com.sgcc.ln.pmos.mobileapp.dialog.RiskNotifyDialog;
import com.sgcc.ln.pmos.mobileapp.presenter.VideoAttestationPresenter;
import com.sgcc.ln.pmos.mobileapp.utils.CameraController;
import com.sgcc.ln.pmos.mobileapp.widget.AutoFitTextureView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

@Route(path = AppArouterPath.APP_VIDEOATTESTATIONACTIVITY)
public class VideoAttestationActivity extends MvpBaseActivity<VideoAttestationPresenter> implements VideoAttestationContract.View {

    private TitleBar titleBar;
    private TextView tvVerifyCode;
    private AutoFitTextureView autoFitTextureView;
    private TextView tvCountDown;
    private TextView tvLast;
    private TextView tvRetry;
    private TextView tvNext;
    private CountDownTimer countDownTimer;//开始倒计时 321
    private CountDownTimer countDownTimer1;// 15秒时长倒计时


    private CameraController mCameraController;
    private String session_id;

    @Autowired
    public String realName;
    @Autowired
    public String idCordNumber;

    @Autowired
    public String fileId;

    @Autowired
    public String telephone;

    @Autowired
    public String officePhone;

    @Autowired
    public String email;

    @Autowired
    public String contactType;

    @Autowired
    public String remarks;

    @Autowired
    public int isCommomContact;

    @Autowired
    public String guid;

    private LoadingPopupView loadingPopup;

    private boolean isShowRisk = true;//是否显示协议弹窗

    private boolean isStart = false;//是否直接开始录制视频

    private boolean isFailed = false;//是否识别失败


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_video_attestation;
    }


    @Override
    protected VideoAttestationPresenter createPresenter() {
        return new VideoAttestationPresenter();
    }

    @Override
    protected void initViews() {
        super.initViews();
        titleBar = findViewById(R.id.titleBar);
        tvVerifyCode = findViewById(R.id.tvVerifyCode);
        autoFitTextureView = findViewById(R.id.autoFitTextureView);
        tvCountDown = findViewById(R.id.tvCountDown);
        tvRetry = findViewById(R.id.tvRetry);
        tvLast = findViewById(R.id.tvLast);
        tvNext = findViewById(R.id.tvNext);


    }


    @Override
    protected void initData() {
        super.initData();
        titleBar.setTitle("新增联系人");
        titleBar.setRightIcon(R.mipmap.go_main, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goMainActivity();
            }
        });
        mPresenter.getCode(realName, idCordNumber);
        XXPermissionsUtil.recordVideo(this, new XXPermissionsUtil.PermissionCallback() {
            @Override
            public void Call() {
                mCameraController = CameraController.getInstance(VideoAttestationActivity.this);
                File video = getExternalFilesDir("video");
                mCameraController.setFolderPath(video.getAbsolutePath());
                mCameraController.initCamera(autoFitTextureView);
            }
        });

        tvNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isFailed) {
                    ToastUtils.showLong("验证失败，请点击【重试】按钮重新开始录制");
                    return;
                }
                stopVideo();
                submit();
            }
        });

        tvLast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopVideo();
                finish();
            }
        });

        tvRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogUtil.showConfirm(mContext, "提示", "确定重新拍摄吗?",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                isShowRisk = false;
                                isStart = true;
                                stopVideo();
                                mPresenter.getCode(realName, idCordNumber);

                            }
                        });

            }
        });


    }

    private void showRisk(int type) {
        new XPopup.Builder(mContext)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .dismissOnTouchOutside(false)
                .dismissOnBackPressed(false)
                .asCustom(new RiskNotifyDialog(this, type, new RiskNotifyDialog.OnClickListener() {
                    @Override
                    public void onConfirm() {
                        if (type == 0) {
                            showRisk(1);
                        }
                        if (type == 1) {
                            countDown();
                            isShowRisk = false;
                        }
                    }
                })).show();
    }


    private void countDown() {
        tvCountDown.setVisibility(View.VISIBLE);
        countDownTimer = new CountDownTimer(3000, 1000) {
            @Override
            public void onTick(long l) {
                tvCountDown.setText(l / 1000 + 1 + "");
            }

            @Override
            public void onFinish() {
                tvCountDown.setVisibility(View.GONE);
                checkPermissions();

            }
        };
        countDownTimer.start();
    }


    @Override
    public void checkResultSuccess(String text) {
        dismissLoad();


        File file1 = new File(mCameraController.getVideoPath());
        if (file1.exists())//上传成功删除压缩的文件
            file1.delete();
        ToastUtils.showShort("实名认证成功");
        saveLinkmanInfo();

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (null != countDownTimer1) {
            countDownTimer1.cancel();
            countDownTimer1 = null;
        }
    }


    private void stopVideo() {
        if (!mCameraController.isStop()) {
            mCameraController.stopRecordingVideo();
        }
        if (null != countDownTimer1) {
            countDownTimer1.cancel();
            countDownTimer1 = null;
        }
    }

    @Override
    public void getCodeSuccess(FaceGetCodeBean.CodeBeam codeBeam) {
        if (isShowRisk)
            showRisk(0);
        if (isStart) {
            countDown();
        }
        session_id = codeBeam.getResult().getSession_id();
        tvVerifyCode.setText(codeBeam.getResult().getCode());
    }

    @Override
    public void onFailed(int code) {
        dismissLoad();
        isFailed = true;
        if (code == 3) {
            File file1 = new File(mCameraController.getVideoPath());
            if (file1.exists())
                file1.delete();
        }  else if (code == 2202) {
            new XPopup.Builder(mContext)
                    .isDestroyOnDismiss(true)
                    .asConfirm("提示", "已到日最大调用次数，请明日再试！",
                            "", "知道了",
                            new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    finish();
                                }
                            }, null, true).show();
        }
    }


    private void checkPermissions() {
        XXPermissionsUtil.recordVideo(this, new XXPermissionsUtil.PermissionCallback() {
            @Override
            public void Call() {
                mCameraController.startRecordingVideo();
                isFailed = false;
                videoCountDown();
            }
        });
    }

    private void videoCountDown() {
        countDownTimer1 = new CountDownTimer(15000, 1000) {
            @Override
            public void onTick(long l) {
                LogUtils.d("十五秒倒计时=" + l / 1000);

            }

            @Override
            public void onFinish() {
                if (!mCameraController.isStop()) {
                    mCameraController.stopRecordingVideo();
                }
                new XPopup.Builder(mContext)
                        .isDestroyOnDismiss(true)
                        .asConfirm("提示", "视频长度已经到最长限制，是否使用该视频进行验证？",
                                "重拍", "使用",
                                new OnConfirmListener() {
                                    @Override
                                    public void onConfirm() {
                                        submit();
                                    }
                                }, new OnCancelListener() {
                                    @Override
                                    public void onCancel() {
                                        countDown();
                                    }
                                }, false).show();


            }
        };
        countDownTimer1.start();
    }


    private void submit() {
        showLoad();
        String s2 = null;
        try {
            s2 = SysUtil.encodeBase64File(new File(mCameraController.getVideoPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (TextUtils.isEmpty(s2)) {
            ToastUtils.showShort("请重新录制视频");
            return;
        }
        mPresenter.checkResult(session_id, realName, idCordNumber, s2);


    }

    private void showLoad() {
        if (loadingPopup == null) {
            loadingPopup = (LoadingPopupView) new XPopup.Builder(mContext)
                    .dismissOnBackPressed(false)
                    .isLightNavigationBar(true)
                    .isViewMode(true)
//                            .asLoading(null, R.layout.custom_loading_popup)
                    .asLoading("")
                    .show();
        } else {
            loadingPopup.show();
        }
    }

    private void dismissLoad() {
        if (null != loadingPopup && loadingPopup.isShow()) {
            loadingPopup.dismiss();
        }
    }


    public void saveLinkmanInfo() {
        Map<String, Object> params = new HashMap<>();
        params.put("contactName", realName);
        params.put("contactType", contactType);
        params.put("email", email);
        params.put("isCommomContact", isCommomContact);
        params.put("officePhone", officePhone);
        params.put("remarks", remarks);
        params.put("doucumentNumber", idCordNumber);
        params.put("telephone", telephone);
        if (!TextUtils.isEmpty(guid))
            params.put("guid", guid);
        params.put("fileId", fileId);


        HttpRequestUtils.getInstance().request(params, HttpInterConst.SAVELINKMANINFO, new MvcNetCallback<DoLoginReleaseBean>(true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
            }

            @Override
            public void onResponse(DoLoginReleaseBean response, int id) {
                super.onResponse(response, id);
                if (response != null) {
                    if (response.getStatus() == 0 && "Success".equals(response.getMessage())) {
                        EventBus.getDefault().post(new EventCenter<>(ArguConstant.SAVE_CONTACT_BACK));
                        ActivityUtils.finishActivity(AddOrEditContactActivity.class);
                        finish();
                    }
                }
            }
        });
    }


}